/*
 * File:   newmain.c
 * Author: Andras Veres
 *
 * Wactchdog code written for PIC12F683
 * If there is no level change on port5 within 1 second, port4 goes down
 * There is a weak pull-up on the input port
 *
 * Created on 2013. augusztus 10., 9:50
 */

#include <stdio.h>
#include <stdlib.h>

#include <xc.h>

// CONFIG
#pragma config FOSC = INTOSCIO  // Oscillator Selection bits (INTOSCIO oscillator: I/O function on RA4/OSC2/CLKOUT pin, I/O function on RA5/OSC1/CLKIN)
#pragma config WDTE = OFF       // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF      // Power-up Timer Enable bit (PWRT disabled)
#pragma config MCLRE = ON       // MCLR Pin Function Select bit (MCLR pin function is MCLR)
#pragma config CP = OFF         // Code Protection bit (Program memory code protection is disabled)
#pragma config CPD = OFF        // Data Code Protection bit (Data memory code protection is disabled)
#pragma config BOREN = OFF      // Brown Out Detect (BOR disabled)
#pragma config IESO = ON        // Internal External Switchover bit (Internal External Switchover mode is enabled)
#pragma config FCMEN = ON       // Fail-Safe Clock Monitor Enabled bit (Fail-Safe Clock Monitor is enabled)

#define _XTAL_FREQ 4000000
#define IN  GPIObits.GP5
#define OUT GPIObits.GP4

/*
 *
 */
int main(int argc, char** argv) {


    GPIO = 0;           // init GPIO
    CMCON0 = 0x07;      // Switch off comaparator on outputs
    ANSEL = 0;          // Set all analog pins to digital (not use as AD inputs)
    TRISIO = 0b00100000;         // Set all IO ports as output except port5

    OPTION_REGbits.nGPPU = 0; // GPIO pull-ups are individually set by
    WPUbits.WPU5 = 0;         // pul-up enabled on port 5

    T1CONbits.TMR1ON = 1;
    T1CONbits.TMR1CS = 1; // Use T1CKI pin as input
    T1CONbits.T1CKPS = 0; // Prescale 1
    T1CONbits.nT1SYNC = 1; // Async mode

    int i;
    int d=128;

    while(1) {
       i = TMR1H;

       if(i%d<d/2) OUT = 1;
       else OUT = 2;

    }

    while(1);

}